package gis.uzd_1;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.prefs.Preferences;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.geotools.data.FeatureSource;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import net.miginfocom.swing.MigLayout;

/**
 * Tower form panel.
 * 
 * @version 0.1
 * @date 2010-05-13
 * @author Edmundas Matusevicius
 */
public class TowerPanel extends JPanel {
    public TowerPanel(JDialog dialog) {
        // save owner dialog
        dlg = dialog;
        
        // set up layout manager
        MigLayout layout = new MigLayout(
                "wrap 3",
                "[]10[70!]5[]");
        setLayout(layout);
        
        // configure list
        lst.setVisibleRowCount(4);
        
        setUpForm();
        setUpActions();
    }
    
    private void setUpForm() {
        // add components
        
        add(lbl1);
        add(scrollPane, "span 1 3, grow");
        add(btn1, "w 72!");
        add(btn2, "cell 2 1, w 72!");
        
        add(new JLabel(" "), "grow");
        add(new JLabel(" "), "grow");
        
        add(lbl2);
        add(txtf1, "span 2, growx");
        
        add(lbl3);
        add(lbl8);
        add(btn3, "w 72!");
        
        add(lbl4);
        add(lbl9);
        add(btn4, "w 72!");
        
        add(lbl5);
        add(txtf2, "span 2, growx");
        
        add(lbl6);
        add(txtf3, "span 2, growx");
        
        add(lbl7);
        add(txtf4, "span 2, growx");
        
        add(btn5, "cell 1 9, w 72!, align right");
        add(btn6, "cell 2 9, w 72!, align right");
    }
    
    private void setUpActions() {
        // add layer button event
        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addShapeFiles();
            }
        });
        
        // remove layer button event
        btn2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Object[] selectedItems = lst.getSelectedValues();
                for (Object sItem : selectedItems) {
                    for (FeatureSource<SimpleFeatureType, SimpleFeature> fs : bufferLayers) {
                        if (fs.getInfo().getTitle().equals(sItem.toString().toLowerCase())) {
                            bufferLayers.remove(fs);
                            break;
                        }
                    }
                    lmdl.removeElement(sItem);
                }
            }
        });
        
        // choose relief layer button event
        btn3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                reliefLayer = addShapeFile(lbl8);
            }
        });
        
        // choose crests layer button event
        btn4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                crestLayer = addShapeFile(lbl9);
            }
        });
        
        // find button event
        btn5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TowerLogic towerLogic = new TowerLogic();
                
                towerLogic.setBufferData(bufferLayers);
                towerLogic.setReliefData(reliefLayer);
                towerLogic.setCrestData(crestLayer);
                
                towerLogic.setObjectBufferization(Integer.parseInt(txtf1.getText()));
                towerLogic.setWirelessCoverage(Integer.parseInt(txtf2.getText()));
                towerLogic.setTowerHeight(Integer.parseInt(txtf3.getText()));
                towerLogic.setTowerRange(Integer.parseInt(txtf4.getText()));
                
                closeDialog();
                
                towerLogic.run();
            }
        });
        
        // cancel button event
        btn6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                closeDialog();
            }
        });
    }
    
    private void closeDialog() {
        dlg.dispatchEvent(new WindowEvent(dlg, WindowEvent.WINDOW_CLOSING));
    }
    
    private void addShapeFiles() {
        // get browse directory
        String dir = node.get("tower_dir", ".");
        
        JFileChooser fileChooser = new JFileChooser();
        
        // set file chooser options
        
        fileChooser.setCurrentDirectory(new File(dir));
        
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("AUX files (*.aux)", "aux"));
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Shape files (*.shp)", "shp"));
        
        fileChooser.setMultiSelectionEnabled(true);
        
        int result = fileChooser.showOpenDialog(null);
        
        // set browse directory
        node.put("tower_dir", fileChooser.getCurrentDirectory().toString());
        
        if (result == JFileChooser.APPROVE_OPTION) {
            File[] files = fileChooser.getSelectedFiles();
            
            for (int i = 0; i < files.length; i++) {
                try {
                    System.out.println(files[i]);
                    // prepare file name
                    
                    String fileName = files[i].getName();
                    fileName = fileName.substring(0, fileName.indexOf("."));
                    fileName = fileName.toLowerCase();
                    
                    String firstChar = fileName.substring(0, 1).toUpperCase();
                    
                    fileName = firstChar.concat(fileName.substring(1));
                    
                    // add to map
                    
                    FileDataStore dataStore = FileDataStoreFinder.getDataStore(files[i]);
                    bufferLayers.add(dataStore.getFeatureSource());
                    
                    // add to layer list
                    
                    lmdl.addElement(fileName);
                } catch (IOException e) {
//                    e.printStackTrace();
                }
            }
        }
    }
    
    private FeatureSource<SimpleFeatureType, SimpleFeature> addShapeFile(JLabel label) {
        // get browse directory
        String dir = node.get("tower_dir", ".");
        
        JFileChooser fileChooser = new JFileChooser();
        
        // set file chooser options
        
        fileChooser.setCurrentDirectory(new File(dir));
        
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("AUX files (*.aux)", "aux"));
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Shape files (*.shp)", "shp"));
        
        fileChooser.setMultiSelectionEnabled(true);
        
        int result = fileChooser.showOpenDialog(null);
        
        // set browse directory
        node.put("tower_dir", fileChooser.getCurrentDirectory().toString());
        
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            
            System.out.println(file);
            
            try {
                // prepare file name
                
                String fileName = file.getName();
                fileName = fileName.substring(0, fileName.indexOf("."));
                fileName = fileName.toLowerCase();
                
                String firstChar = fileName.substring(0, 1).toUpperCase();
                
                fileName = firstChar.concat(fileName.substring(1));
                
                // add layer name
                
                label.setText(fileName);
                
                // return data
                
                FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
                return dataStore.getFeatureSource();
            } catch (IOException e) {
//                    e.printStackTrace();
            }
        }
        
        return null;
    }
    
    // feature sources
    
    private ArrayList<FeatureSource<SimpleFeatureType, SimpleFeature>> bufferLayers = new ArrayList<FeatureSource<SimpleFeatureType, SimpleFeature>>();
    private FeatureSource<SimpleFeatureType, SimpleFeature> reliefLayer;
    private FeatureSource<SimpleFeatureType, SimpleFeature> crestLayer;
    
    // dialog
    
    private JDialog dlg;
    
    // labels
    
    private JLabel lbl1 = new JLabel("Bufferize layers");
    private JLabel lbl2 = new JLabel("Bufferization (m)");
    private JLabel lbl3 = new JLabel("Relief layer");
    private JLabel lbl4 = new JLabel("Crest layer");
    private JLabel lbl5 = new JLabel("Wireless coverage (%)");
    private JLabel lbl6 = new JLabel("Tower height (m)");
    private JLabel lbl7 = new JLabel("Station range (m)");
    private JLabel lbl8 = new JLabel("");
    private JLabel lbl9 = new JLabel("");
    
    // text fields
    
    private JTextField txtf1 = new JTextField();
    private JTextField txtf2 = new JTextField();
    private JTextField txtf3 = new JTextField();
    private JTextField txtf4 = new JTextField();
    
    // buttons
    
    private JButton btn1 = new JButton("Add");
    private JButton btn2 = new JButton("Remove");
    private JButton btn3 = new JButton("Choose");
    private JButton btn4 = new JButton("Choose");
    private JButton btn5 = new JButton("Find");
    private JButton btn6 = new JButton("Cancel");
    
    // list
    
    private DefaultListModel lmdl = new DefaultListModel();
    private JList lst = new JList(lmdl);
    private JScrollPane scrollPane = new JScrollPane(lst);
    
    // application preferences
    
    private Preferences root = Preferences.userRoot();
    private final Preferences node = root.node("/gis");
}
